<template>
  <div class="app-container">
    <!-- 供应商信息维护 -->

    <div class="search-bar" px-8>
      <!-- 搜索 -->
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="供应商编号" prop="code">
          <el-select-v2
            v-model="queryParams.code"
            filterable
            clearable
            :options="allCompanyCode"
            value-key="value"
            :props="codeProps"
            placeholder="请输入供应商编号"
            class="!w-[192px]"
            @change="handleQuery()"
          />
        </el-form-item>

        <el-form-item label="供应商名称" prop="companyName">
          <el-input
            v-noSpace
            v-model="queryParams.companyName"
            placeholder="请输入供应商名称"
            clearable
            class="!w-[192px]"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            class="!w-[192px]"
            filterable
            clearable
            @change="handleQuery"
          >
            <el-option
              v-for="item in companyStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="供应商属性" prop="suppType">
          <el-select
            v-model="querySuppType"
            placeholder="请选择供应商属性"
            class="w-full"
            filterable
            multiple
            clearable
            @change="handleQuery"
          >
            <el-option
              v-for="item in suppTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item> -->

        <el-form-item label="业务员" prop="salesMan">
          <el-select
            v-model="queryParams.salesMan"
            filterable
            clearable
            placeholder="请输入业务员"
            class="!w-[192px]"
            @change="handleQuery()"
          >
            <el-option
              v-for="item in salesPersonList"
              :key="item.value"
              :label="item.label"
              :value="item.value.toString()"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="录入日期" prop="inputTime">
          <el-date-picker
            v-model="queryParams.inputTime"
            type="daterange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleQuery()"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
          <el-button
            type="warning"
            icon="menu"
            @click="handleOpenDialog"
            v-hasPerm="'sys:suppInfo:edit'"
          >
            新增
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 供应商列表 -->
    <el-card shadow="never">
      <el-table v-loading="loading" :data="pageData" show-overflow-tooltip>
        <el-table-column prop="code" label="供应商编号" min-width="180" align="center" />
        <el-table-column prop="companyName" label="中文名称" min-width="120" align="center" />
        <el-table-column prop="nickName" label="简称" min-width="120" align="center" />
        <el-table-column prop="contactPerson" label="主要联系人" min-width="120" align="center" />
        <el-table-column prop="status" label="供应商状态" align="center" min-width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.status == 1" type="warning">风险供应商</el-tag>
            <el-tag v-if="scope.row.status == 2" type="danger">失信供应商</el-tag>
            <el-tag v-if="scope.row.status == 0" type="success">正常供应商</el-tag>
            <el-tag v-if="scope.row.status == 3" type="success">意向供应商</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="suppType" label="供应商属性" align="center" min-width="120">
          <template #default="scope">
            <div v-if="scope.row.suppType">
              <el-tag v-for="type in scope.row.suppType?.split(',')">
                {{ getSuppTypeLabels(type) }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="salesMan" label="业务员" min-width="120" align="center">
          <template #default="scope">
            {{
              salesPersonList.filter((item) => item.value.toString() == scope.row.salesMan)[0]
                ?.label
            }}
          </template>
        </el-table-column>

        <el-table-column prop="suppScore" label="供应商评分" align="center" min-width="120" />
        <el-table-column prop="suppLevel" label="供应商等级" align="center" min-width="120">
          <template #default="scope">
            {{ getSuppLevelLabels(scope.row.suppLevel) }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="录入时间" align="center" min-width="180" />
        <el-table-column label="操作" min-width="300px" fixed="right" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              link
              size="small"
              @click="handleOpenDialog(scope.row, 'look')"
            >
              查看
            </el-button>
            <el-button
              type="primary"
              link
              size="small"
              @click="handleOpenFollowDialog(scope.row)"
              v-hasPerm="'sys:suppInfo:fol'"
            >
              跟进
            </el-button>
            <el-button
              type="primary"
              link
              size="small"
              @click="handleOpenFollowViewDialog(scope.row)"
            >
              跟进查看
            </el-button>
            <el-button
              type="warning"
              link
              size="small"
              @click="handleOpenDialog(scope.row, 'update')"
              v-hasPerm="'sys:suppInfo:edit'"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
              v-hasPerm="'sys:suppInfo:del'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 查看，新增 -->
    <el-dialog
      v-model="infoDialog.visible"
      :title="infoDialog.title"
      width="800px"
      @close="handleCloseDialog"
    >
      <el-tabs v-model="activeTabsName" class="demo-tabs" @tab-click="handleTabsClick">
        <el-tab-pane label="基础信息" name="基础信息">
          <el-form
            ref="infoFormRef"
            :model="infoFormData"
            label-width="100px"
            :disabled="infoDialog.type == 'look' || submitButtonDisabled == true"
            :rules="infoRules"
          >
            <el-row mt-8>
              <el-col :span="12">
                <el-form-item label="中文名称" prop="companyName" label-width="140px">
                  <el-input
                    v-noSpace
                    v-model="infoFormData.companyName"
                    placeholder="请输入中文名称"
                    :maxlength="50"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="简称" prop="nickName" label-width="140px">
                  <el-input
                    v-noSpace
                    v-model="infoFormData.nickName"
                    placeholder="请输入简称"
                    :maxlength="15"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="英文名称" prop="otherName" label-width="140px">
                  <el-input
                    v-noSpace
                    v-model="infoFormData.otherName"
                    placeholder="请输入英文名称"
                    :maxlength="50"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="状态" prop="status" label-width="140px">
                  <el-select v-model="infoFormData.status" placeholder="请选择状态">
                    <el-option
                      v-for="item in companyStatus"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="营业执照代码" prop="businessLicenseNo" label-width="140px">
                  <el-input
                    v-noSpace
                    v-model="infoFormData.businessLicenseNo"
                    placeholder="请填写营业执照代码"
                    maxlength="18"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="供应商属性" prop="checkedSuppTypes" label-width="140px">
                  <el-checkbox
                    v-model="checkAll"
                    :indeterminate="isIndeterminate"
                    @change="handleCheckAllChange"
                    style="margin-right: 20px"
                  >
                    全选
                  </el-checkbox>

                  <el-checkbox-group v-model="checkedSuppTypes" @change="handleCheckedTypesChange">
                    <el-checkbox
                      v-for="type in suppTypeList"
                      :key="type.value"
                      :label="type.label"
                      :value="type.value"
                    >
                      {{ type.label }}
                    </el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="供应商评分" prop="suppScore" label-width="140px">
                  <el-input
                    v-noSpace
                    v-model.number="infoFormData.suppScore"
                    placeholder="请输入供应商评分"
                    type="number"
                    :min="0"
                    :max="100"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="供应商等级" prop="suppLevel" label-width="140px">
                  <el-select v-model="infoFormData.suppLevel" placeholder="请选择供应商等级">
                    <el-option
                      v-for="item in supplierLevel"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="授信截止时间" prop="creditDeadline" label-width="140px">
                  <el-date-picker
                    v-model="infoFormData.creditDeadline"
                    type="date"
                    placeholder="选择日期"
                    style="width: 100%"
                    value-format="YYYY-MM-DD"
                    picker-options="pickerOptions"
                    :disabled-date="disabledDate"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="业务员" prop="salesMan" label-width="140px">
                  <el-select
                    v-model="infoFormData.salesMan"
                    filterable
                    clearable
                    placeholder="请输入业务员"
                  >
                    <el-option
                      v-for="item in salesPersonList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value.toString()"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="公司网站" prop="website" label-width="140px">
                  <el-input
                    v-noSpace
                    v-model="infoFormData.website"
                    placeholder="请输入公司网站"
                    :maxlength="50"
                  >
                    <template #prepend>Http://</template>
                  </el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="对应财务系统编号" prop="accCode" label-width="140px">
                  <el-input
                    v-noSpace
                    v-model="infoFormData.accCode"
                    placeholder="请输入对应财务系统编号"
                    :maxlength="20"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="对应财务系统名称" prop="accName" label-width="140px">
                  <el-input
                    v-noSpace
                    v-model="infoFormData.accName"
                    placeholder="请输入对应财务系统名称"
                    :maxlength="30"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="银行账号" prop="bankInfo" label-width="140px">
                  <el-input
                    v-noSpace
                    v-model="infoFormData.bankInfo"
                    placeholder="请输入银行账号"
                    :maxlength="30"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="开户银行" prop="bankName" label-width="140px">
                  <el-input
                    v-noSpace
                    v-model="infoFormData.bankName"
                    placeholder="请输入银行账号"
                    :maxlength="20"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="18">
                <el-form-item label="附件" prop="fileInfoJson" label-width="140px">
                  <div v-if="infoFormData.fileInfoJson" style="width: 100%">
                    <el-row
                      v-for="(item, index) in JSON.parse(infoFormData.fileInfoJson)"
                      :key="index"
                    >
                      <el-col :span="12">
                        <el-text type="primary">{{ item.name }}</el-text>
                      </el-col>
                      <el-col :span="12">
                        <el-link type="primary" @click="downloadFile(item.name, item.url)">
                          下载
                        </el-link>
                        <el-link type="danger" @click="deleteFile(index)" class="ml-4">
                          删除
                        </el-link>
                      </el-col>
                    </el-row>
                  </div>
                  <div v-else style="width: 100%">
                    <el-row />
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <FileUpload
                  v-if="infoDialog.type !== 'look'"
                  v-model:model-value="fileInfoJson"
                  uploadBtnText="点击上传"
                  :showTip="true"
                  :data="{ bizType: 'contract' }"
                  :maxSize="5 * 1024 * 1024"
                  :showFileList="false"
                  @update:modelValue="handleUpdateFileInfoJson"
                />
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注" prop="remark" label-width="140px">
                  <el-input
                    v-noSpace
                    v-model="infoFormData.remark"
                    type="textarea"
                    placeholder="请输入备注"
                    maxlength="500"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <div v-if="infoDialog.type !== 'look'" class="flex-center">
              <el-button v-debounce="handleSubmitBase" type="primary">提 交</el-button>
            </div>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="地址信息" name="地址信息">
          <el-scrollbar height="500px">
            <el-button
              v-if="infoDialog.type !== 'look'"
              type="primary"
              @click="handleOpenAddressDialog"
            >
              新增收货地址
            </el-button>
            <div class="bg-gray-50 p-3">
              <div class="mx-auto max-w-4xl">
                <div class="grid gap-4">
                  <div
                    v-for="(address, index) in addressList"
                    :key="index"
                    class="bg-white rounded-lg shadow-sm p-6 relative"
                  >
                    <!-- 第一行 -->
                    <div class="flex items-center justify-between mb-4">
                      <div class="flex items-center space-x-4">
                        <span class="text-lg font-medium">
                          {{ address.contactPerson }} - {{ address.tel }}
                        </span>
                        <div class="flex gap-2">
                          <span
                            v-if="address.isDefault"
                            class="px-2 py-1 bg-blue-100 text-blue-600 text-xs rounded-md"
                          >
                            默认地址
                          </span>
                          <span
                            v-if="address.isShipping"
                            class="px-2 py-1 bg-green-100 text-green-600 text-xs rounded-md"
                          >
                            送货地址
                          </span>
                          <span
                            v-if="address.isBilling"
                            class="px-2 py-1 bg-purple-100 text-purple-600 text-xs rounded-md"
                          >
                            账单地址
                          </span>
                        </div>
                      </div>
                      <el-button
                        v-if="infoDialog.type !== 'look'"
                        class="text-gray-400 hover:text-gray-600 transition-colors"
                        link
                        @click="deleteAddress(address.id)"
                      >
                        <el-icon>
                          <Close />
                        </el-icon>
                      </el-button>
                    </div>
                    <!-- 第二行 -->
                    <div class="text-gray-600 mb-3">
                      {{ address.address }}
                    </div>
                    <!-- 第三行 -->
                    <!-- <div class="text-gray-600 mb-2">
                      <span class="inline-block w-20 text-gray-400">联系人：</span>
                      {{ address.contactPerson }}
                    </div> -->
                    <!-- 第四行 -->
                    <!-- <div class="text-gray-600 mb-2">
                      <span class="inline-block w-20 text-gray-400">联系电话：</span>
                      {{ address.tel }}
                    </div> -->
                    <!-- 第五行 -->
                    <div class="text-gray-600 mb-2">
                      <span class="inline-block w-20 text-gray-400">电子邮箱：</span>
                      {{ address.email || "-" }}
                    </div>
                    <!-- 第六行 -->
                    <div class="bg-gray-50 pt-2 pb-2 rounded-md mb-4 text-gray-600 text-sm">
                      <span class="text-gray-400">备注：</span>
                      {{ address.remark }}
                    </div>
                    <!-- 第七行 -->
                    <div v-if="infoDialog.type !== 'look'" class="flex justify-end gap-4">
                      <el-button
                        v-if="!address.isShipping"
                        link
                        type="success"
                        @click="updateAddress('isShipping', address)"
                      >
                        <el-icon>
                          <Location />
                        </el-icon>
                        <span>设为送货地址</span>
                      </el-button>
                      <el-button
                        v-if="!address.isBilling"
                        link
                        type="success"
                        @click="updateAddress('isBilling', address)"
                      >
                        <el-icon>
                          <Wallet />
                        </el-icon>
                        <span>设为账单地址</span>
                      </el-button>
                      <el-button
                        v-if="!address.isDefault"
                        link
                        type="primary"
                        @click="updateAddress('isDefault', address)"
                      >
                        <el-icon>
                          <Star />
                        </el-icon>
                        <span>设为默认地址</span>
                      </el-button>
                      <el-button
                        link
                        type="primary"
                        @click="handleOpenAddressDialog(address, 'edit')"
                      >
                        <el-icon>
                          <Edit />
                        </el-icon>
                        <span>编辑</span>
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-scrollbar>
        </el-tab-pane>
        <el-tab-pane label="联系人信息" name="联系人信息">
          <el-scrollbar max-height="500px">
            <el-button
              v-if="infoDialog.type !== 'look'"
              type="primary"
              @click="handleOpenContactDialog"
            >
              新增联系人
            </el-button>
            <div class="min-h-screen bg-gray-50 py-8 px-4">
              <div class="mx-auto max-w-4xl">
                <div class="grid gap-6">
                  <div
                    v-for="(contact, index) in contactList"
                    :key="index"
                    class="bg-white rounded-lg shadow-sm p-6 relative"
                  >
                    <!-- 第一行 -->
                    <div class="flex items-center justify-between mb-4">
                      <div class="flex items-center space-x-4">
                        <span class="text-lg font-medium">{{ contact.contactPerson }}</span>
                        <div class="flex gap-2" v-if="contact.department">
                          <span class="px-2 py-1 bg-blue-100 text-blue-600 text-xs rounded-md">
                            {{ contact.department }}
                          </span>
                        </div>
                      </div>
                      <el-button
                        v-if="infoDialog.type !== 'look'"
                        link
                        class="text-gray-400 hover:text-gray-600 transition-colors"
                        @click="deleteContact(contact.id)"
                      >
                        <el-icon>
                          <Close />
                        </el-icon>
                      </el-button>
                    </div>
                    <!-- 第二行 -->
                    <!-- <div class="text-gray-600 mb-2">
                      <span class="inline-block w-20 text-gray-400">部门：</span>
                      {{ contact.department || "-" }}
                    </div> -->
                    <!-- 第三行 -->
                    <div class="text-gray-600 mb-2">
                      <span class="inline-block w-20 text-gray-400">职位：</span>
                      {{ contact.position || "-" }}
                    </div>
                    <!-- 第四行 -->
                    <div class="text-gray-600 mb-2">
                      <span class="inline-block w-20 text-gray-400">联系电话：</span>
                      {{ contact.tel || "-" }}
                    </div>
                    <!-- 第五行 -->
                    <div class="text-gray-600 mb-2">
                      <span class="inline-block w-20 text-gray-400">电子邮箱：</span>
                      {{ contact.email || "-" }}
                    </div>
                    <!-- 第六行 -->
                    <div class="bg-gray-50 pt-2 pb-2 rounded-md mb-4 text-gray-600 text-sm">
                      <span class="text-gray-400">备注：</span>
                      {{ contact.remark || "-" }}
                    </div>
                    <!-- 第七行 -->
                    <div v-if="infoDialog.type !== 'look'" class="flex justify-end gap-4">
                      <el-button
                        link
                        type="warning"
                        class="flex items-center space-x-2 text-blue-600 hover:text-blue-700 transition-colors !rounded-button whitespace-nowrap"
                        @click="handleOpenContactDialog(contact)"
                      >
                        <el-icon>
                          <Edit />
                        </el-icon>
                        <span>编辑</span>
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-scrollbar>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <!-- 地址信息弹窗 -->
    <el-dialog
      v-model="addressDialog.visible"
      :title="addressDialog.title"
      width="500px"
      @close="handleCloseAddressDialog"
    >
      <el-form
        ref="addressRef"
        :model="addressParams"
        :disabled="infoDialog.type == 'look'"
        :rules="addressRules"
      >
        <!-- <el-form-item label="地址" prop="addressName" label-width="80px">
          <el-input v-noSpace v-model="addressParams.addressName" placeholder="请输入地址" />
        </el-form-item> -->
        <el-form-item label="详细地址" prop="address" label-width="80px">
          <!-- <el-input v-noSpace v-model="addressParams.address" placeholder="请输入详细地址" /> -->
          <area-select
            :model-value="addressParams.address"
            @get-address="handleGetAdress"
          ></area-select>
        </el-form-item>

        <el-form-item label="联系人" prop="contactPerson" label-width="80px">
          <el-input
            v-noSpace
            v-model="addressParams.contactPerson"
            placeholder="请输入联系人"
            :maxlength="20"
          />
        </el-form-item>

        <el-form-item label="联系电话" prop="tel" label-width="80px">
          <el-input
            v-noSpace
            v-model="addressParams.tel"
            placeholder="请输入联系电话"
            :maxlength="20"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email" label-width="80px">
          <el-input
            v-noSpace
            v-model="addressParams.email"
            placeholder="请输入邮箱"
            :maxlength="20"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark" label-width="80px">
          <el-input
            v-noSpace
            v-model="addressParams.remark"
            type="textarea"
            placeholder="请输入备注"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="" label-width="80px">
          <el-checkbox
            v-model="addressParams.isDefault"
            label="默认地址"
            :true-value="1"
            :false-value="0"
            size="large"
          />

          <el-checkbox
            v-model="addressParams.isBilling"
            label="账单地址"
            :true-value="1"
            :false-value="0"
            size="large"
          />
          <el-checkbox
            v-model="addressParams.isShipping"
            label="送货地址"
            :true-value="1"
            :false-value="0"
            size="large"
          />
        </el-form-item>
        <div class="dialog-footer flex-center">
          <el-button type="primary" @click="handleSaveAddress()">保存地址信息</el-button>
        </div>
      </el-form>
    </el-dialog>
    <!-- 联系人信息弹窗 -->
    <el-dialog
      v-model="contactDialog.visible"
      :title="contactDialog.title"
      @close="handleCloseContactDialog"
    >
      <el-form
        ref="contactRef"
        :model="contactPersonParams"
        :disabled="infoDialog.type == 'look'"
        :rules="contactRules"
      >
        <el-form-item label="联系人" prop="contactPerson" label-width="80px">
          <el-input
            v-noSpace
            v-model="contactPersonParams.contactPerson"
            placeholder="请输入联系人"
            :maxlength="20"
          />
        </el-form-item>

        <el-form-item label="部门" prop="department" label-width="80px">
          <el-input
            v-noSpace
            v-model="contactPersonParams.department"
            placeholder="请输入部门"
            :maxlength="20"
          />
        </el-form-item>
        <el-form-item label="职位" prop="position" label-width="80px">
          <el-input
            v-noSpace
            v-model="contactPersonParams.position"
            placeholder="请输入职位"
            :maxlength="20"
          />
        </el-form-item>
        <el-form-item label="联系电话" prop="tel" label-width="80px">
          <el-input
            v-noSpace
            v-model="contactPersonParams.tel"
            placeholder="请输入联系电话"
            :maxlength="20"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email" label-width="80px">
          <el-input
            v-noSpace
            v-model="contactPersonParams.email"
            placeholder="请输入邮箱"
            :maxlength="20"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark" label-width="80px">
          <el-input
            v-noSpace
            v-model="contactPersonParams.remark"
            type="textarea"
            placeholder="请输入备注"
            :maxlength="120"
            show-word-limit
          />
        </el-form-item>
        <div class="dialog-footer flex-center">
          <el-button v-if="infoDialog.type !== 'look'" type="primary" @click="handleSaveContact()">
            保存联系人信息
          </el-button>
        </div>
      </el-form>
    </el-dialog>
    <!-- 跟进弹窗 -->
    <el-dialog
      v-model="followDialog.visible"
      :title="followDialog.title"
      width="500px"
      @close="handleCloseFollowDialog"
    >
      <el-form ref="followRef" :model="followParams" :rules="followRules">
        <el-form-item label="跟进业务员" prop="followContactPerson" label-width="100px">
          <el-select
            v-model="followParams.followContactPerson"
            filterable
            clearable
            placeholder="请输入业务员"
          >
            <el-option
              v-for="item in salesPersonList"
              :key="item.value"
              :label="item.label"
              :value="item.value.toString()"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactType" label-width="100px">
          <el-input
            v-noSpace
            v-model="followParams.contactType"
            type="tel"
            placeholder="请输入联系电话"
          />
        </el-form-item>
        <el-form-item label="跟进时间" prop="followDate" label-width="100px">
          <el-date-picker
            v-model="followParams.followDate"
            style="width: 100%"
            type="datetime"
            placeholder="选择日期时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :disabled-date="disabledDate"
          />
        </el-form-item>

        <el-form-item label="跟进记录" prop="remark" label-width="100px">
          <el-input
            v-noSpace
            v-model="followParams.remark"
            type="textarea"
            placeholder="请输入跟进记录"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <div class="dialog-footer flex-center">
          <el-button type="primary" v-debounce="handleSaveFollow">保存跟进记录</el-button>
        </div>
      </el-form>
    </el-dialog>
    <!-- 跟进查看弹窗 -->

    <el-dialog
      v-model="followViewDialog.visible"
      :title="followViewDialog.title"
      width="90%"
      :show-close="true"
      class="max-w-[500px]"
      @close="handleCloseFollowViewDialog"
    >
      <el-scrollbar max-height="400px">
        <div class="space-y-4">
          <div v-if="followList.length == 0" class="bg-white p-4 rounded-lg shadow flex-center">
            <p class="text-gray-600">暂无跟进记录</p>
          </div>
          <div v-else>
            <div
              v-for="(record, index) in followList"
              :key="index"
              class="bg-white p-4 rounded-lg shadow"
            >
              <div class="flex items-center justify-between mb-2">
                <div class="flex items-center">
                  <span class="font-semibold">
                    跟进人：
                    {{
                      salesPersonList.filter(
                        (ele: any) => ele.value == record.followContactPerson
                      )[0]?.label
                    }}
                  </span>
                </div>
                <span class="text-gray-600">跟进时间：{{ record.followDate }}</span>
              </div>
              <p class="text-gray-600 mb-2">跟进记录：</p>
              <p class="text-gray-700 mb-2">{{ record.remark }}</p>
              <div class="flex justify-end">
                <el-button
                  type="danger"
                  size="small"
                  link
                  class="!rounded-button whitespace-nowrap"
                  @click="deleteRecord(record)"
                >
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </el-scrollbar>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import suppInfoApi, {
  CompanyContact,
  AddressInfo,
  suppInfoPageQuery,
  suppInfoPageVO,
} from "@/api/suppManage/suppInfo";

import type { CheckboxValueType, UploadInstance, UploadUserFile } from "element-plus";
import { FormItemRule } from "element-plus/es";
import type { TabsPaneContext } from "element-plus";
import salesApi, { FollowUp } from "@/api/sales/sales";
import FileAPI from "@/api/file";
import organizationalAPI from "@/api/basicData/organizational";
import UserAPI from "@/api/system/user";
import configApi, { ConfigType } from "@/api/config/config";
import item from "element-plus/es/components/space/src/item";

const querySuppType = ref<string[]>([]);
const checkAll = ref(false);
const isIndeterminate = ref(false);
const checkedSuppTypes = ref();

const getSuppTypeLabels = (suppType: string) => {
  let s = suppTypeList.value.filter((item: any) => {
    return item.value === suppType;
  });
  return s[0]?.label;
};

const handleCheckAllChange = (val: CheckboxValueType) => {
  //选出所有value
  const values = suppTypeList.value.map((item) => item.value);

  checkedSuppTypes.value = val ? values : [];

  isIndeterminate.value = false;
};
const handleCheckedTypesChange = (value: CheckboxValueType[]) => {
  const checkedCount = value.length;
  checkAll.value = checkedCount === suppTypeList.value.length;
  isIndeterminate.value = checkedCount > 0 && checkedCount < suppTypeList.value.length;
};

//基础信息表单校验
const infoRules: Record<string, FormItemRule[]> = {
  //供应商编号
  code: [{ required: true, message: "请输入供应商编号", trigger: "blur" }],
  //跟进业务员
  // salesMan: [{ required: true, message: "请选择业务员", trigger: "change" }],
  //中文名称
  companyName: [{ required: true, message: "请输入中文名称", trigger: "blur" }],

  //状态
  status: [{ required: true, message: "请选择状态", trigger: "change" }],

  businessLicenseNo: [
    { required: true, message: "请输入营业执照代码", trigger: "blur" },
    {
      pattern: /^[0-9A-Z]{18}$/,
      message: "请输入正确的营业执照代码（18位大写字母或数字）",
      trigger: "blur",
    },
  ],

  //英文名称
  otherName: [{ required: true, message: "请输入英文名称", trigger: "blur" }],

  //简称
  nickName: [{ required: true, message: "请输入简称", trigger: "blur" }],
  //主要联系人
  contactPerson: [{ required: true, message: "请输入主要联系人", trigger: "blur" }],

  //授信截止时间
  creditDeadline: [{ required: true, message: "请选择授信截止时间", trigger: "change" }],
  //公司网站
  website: [
    //以www开头

    {
      pattern: /^[a-zA-Z0-9-]+(\.[a-zA-Z]{2,})+(\/.*)?$/,
      message: "请输入正确格式（如：www.example.com 或 example.com）",
      trigger: "blur",
    },
  ],
  //对应财务系统编号
  accCode: [
    {
      required: true,
      message: "请输入对应财务系统编号",
      trigger: "blur",
    },
  ],
  //对应财务系统名称
  accName: [
    {
      required: true,
      message: "请输入对应财务系统名称",
      trigger: "blur",
    },
  ],
  // 银行信息
  bankInfo: [
    {
      required: true,
      message: "请输入银行账号",
      trigger: "blur",
    },
  ],

  //附件
  fileInfoJson: [
    {
      required: true,
      message: "请上传附件",
      trigger: "change",
    },
  ],
  //供应商属性
  suppType: [
    {
      required: true,
      message: "请选择供应商属性",
      trigger: "blur",
    },
  ],
  //供应商评分
  suppScore: [
    {
      required: true,
      message: "请输入供应商评分",
      trigger: "blur",
    },

    { type: "number", min: 0, max: 100, message: "评分范围在0到100之间", trigger: "blur" },
  ],
  //供应商等级
  suppLevel: [
    {
      required: true,
      message: "请选择供应商等级",
      trigger: "blur",
    },
  ],
};

const handleGetAdress = (data: {
  code: string[]; //区域码
  name: string[]; //汉字
  isComplete: boolean; //是否选择完整，方便校验
}) => {
  addressParams.address = data.name.toString();
};
//地址信息校验
const addressRef = ref();
const addressRules: Record<string, FormItemRule[]> = {
  address: [{ required: true, message: "请选择完整地区信息", trigger: ["change", "blur"] }],
  addressName: [
    {
      required: true,
      message: "请输入地址",
      trigger: "blur",
    },
  ],
  contactPerson: [{ required: true, message: "请输入联系人", trigger: "blur" }],
  tel: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    {
      pattern:
        /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/,
      message: "请输入正确的联系电话",
    },
  ],
  email: [
    // { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] },
  ],
  addressType: [
    {
      required: true,
      message: "请选择地址类型",
      trigger: "change,blur",
    },
  ],
};

//联系人信息校验
const contactRef = ref();
const contactRules: Record<string, FormItemRule[]> = {
  contactPerson: [{ required: true, message: "请输入联系人", trigger: "blur" }],
  // department: [{ required: true, message: "请输入部门", trigger: "blur" }],
  // position: [{ required: true, message: "请输入职位", trigger: "blur" }],
  tel: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    {
      pattern:
        /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/,
      message: "请输入正确的联系电话",
    },
  ],
  email: [
    // { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] },
  ],
};

//供应商属性
const suppTypeList = ref<{ value: string; label: string }[]>([]);
//从配置表获取供应商属性
const getSuppTypeList = () => {
  configApi.getConfigListByType(ConfigType.SUPP_TYPE).then((res) => {
    suppTypeList.value = res.map((item: any) => {
      return {
        value: item.codeValue,
        label: item.codeName,
      };
    });
  });
};
//供应商等级列表
const supplierLevel = ref([
  { value: 0, label: "A级" },
  { value: 1, label: "B级" },
  { value: 2, label: "C级" },
  { value: 3, label: "D级" },
]);
const getSuppLevelLabels = (value: number) => {
  return supplierLevel.value.find((item: any) => item.value === value)?.label;
};

//供应商状态列表
const companyStatus = ref([
  { value: 0, label: "正常供应商" },
  { value: 1, label: "风险供应商" },
  { value: 2, label: "失信供应商" },
  { value: 3, label: "意向供应商" },
]);
//所有供应商编号-下拉框
const codeProps = {
  label: "label",
  value: "value",
};
const allCompanyCode = ref<{ code: string; count: number }[]>([]);

//所有业务员-下拉框
const salesPersonList = ref<any[]>([]);

//所有联系人
const allContactList = ref<{ contact_person: string; count: number }[]>([]);
//新增tabs中联系人信息表单
const contactPersonParams = reactive<CompanyContact>({ id: NaN });
//联系人列表
const contactList = ref<CompanyContact[]>([]);

//新增tabs中地址信息表单
const addressParams = reactive<AddressInfo>({ id: NaN });
//地址列表
const addressList = ref<AddressInfo[]>([]);

//跟进弹窗表单
const followParams = reactive<FollowUp>({ id: 0 });
//跟进记录列表
const followList = ref<FollowUp[]>([]);

const queryFormRef = ref(ElForm);
const queryParams = reactive<suppInfoPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

const pageData = ref<suppInfoPageVO[]>();

const total = ref(0);

//弹窗配置
//新增弹窗
const infoDialog = reactive({
  title: "",
  visible: false,
  type: "",
});
//跟进弹窗
const followRef = ref();

const followRules = reactive<Record<string, FormItemRule[]>>({
  followContactPerson: [
    {
      required: true,
      message: "请输入业务员",
      trigger: "blur",
    },
  ],
  contactType: [
    {
      required: true,
      message: "请输入联系电话",
      trigger: "blur",
    },
    {
      pattern:
        /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/,
      message: "请输入正确的联系电话",
    },
  ],
  followDate: [
    {
      required: true,
      message: "请选择跟进日期",
      trigger: ["change", "blur"],
    },
  ],
  remark: [
    //最大500
    { min: 0, max: 500, message: "备注长度在 0 到 500 个字符", trigger: "blur" },
  ],
});

const followDialog = reactive({
  title: "",
  visible: false,
});

//跟进查看弹窗
const followViewDialog = reactive({
  title: "",
  visible: false,
});

//Tabs
const activeTabsName = ref("基础信息");
const handleTabsClick = (tab: TabsPaneContext, event: Event) => {
  if (tab.paneName === "基础信息") {
  } else if (tab.paneName === "地址信息") {
  } else if (tab.paneName === "联系人信息") {
  }
};

//基础信息提交表单
const infoFormRef = ref();
const submitButtonDisabled = ref(false);

const loading = ref(false);

//地址弹窗
const addressDialog = reactive({
  title: "",
  visible: false,
  type: "",
});
// 联系人弹窗
const contactDialog = reactive({
  title: "",
  visible: false,
  type: "",
});

const infoFormData = reactive<suppInfoPageVO>({
  salesMan: "", // 跟进业务员
  companyName: "", // 中文名称
  otherName: "", // 英文名称
  nickName: "", // 简称
  contactPerson: "", // 主要联系人
  status: undefined, // 状态
  creditDeadline: "", // 授信截止时间
  website: "", // 公司网站
  accCode: "", // 对应财务系统编号
  accName: "", // 对应财务系统名称
  bankName: "", //开户银行
  bankInfo: "", // 银行信息
  remark: "", // 备注
  fileInfoJson: "", // 附件信息，初始化为空数组
  suppType: "", // 供应商类型
});

const fileInfoJson = ref<UploadUserFile[]>([]);

// 查询
function handleQuery() {
  loading.value = true;

  const query = { ...queryParams };

  if (queryParams.inputTime && queryParams.inputTime.length === 2) {
    query.startTime = queryParams.inputTime[0];
    query.endTime = queryParams.inputTime[1];
    delete query.inputTime;
  } else {
    query.startTime = undefined;
    query.endTime = undefined;
    delete query.inputTime;
  }
  query.suppType = querySuppType.value.join(",");

  suppInfoApi
    .getPage(query)
    .then((data: any) => {
      pageData.value = [...(data.records as suppInfoPageVO[])];

      total.value = data.total;
    })
    .catch((err) => {
      // ElMessage.error(`${err}`);
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryParams.code = undefined;
  queryParams.salesMan = undefined;
  queryParams.companyName = undefined;
  queryParams.status = undefined;
  queryParams.inputTime = undefined;
  queryParams.suppType = undefined;
  handleQuery();
}

// 新增/修改/查看
function handleOpenDialog(row?: any, type?: string) {
  infoDialog.type = type || "";
  infoDialog.visible = true;
  activeTabsName.value = "基础信息";
  if (type === "look") {
    //查看,不可编辑
    infoDialog.title = "查看供应商信息";
    adCpQueryParams.parentCode = row.code;
    Object.assign(infoFormData, { ...row });
    if (infoFormData.suppType) {
      isIndeterminate.value = true;
      checkedSuppTypes.value = infoFormData.suppType?.split(",");
    }
    if (infoFormData.suppType?.split(",").length == suppTypeList.value.length) {
      checkAll.value = true;
    }
    handleGetInfo();
  } else if (type == "update") {
    //修改
    infoDialog.title = "修改供应商信息";
    adCpQueryParams.parentCode = row.code;
    Object.assign(infoFormData, { ...row });
    if (infoFormData.suppType) {
      isIndeterminate.value = true;
      checkedSuppTypes.value = infoFormData.suppType?.split(",");
    }
    if (infoFormData.suppType?.split(",").length == suppTypeList.value.length) {
      checkAll.value = true;
    }
    handleGetInfo();
    //回显
  } else {
    infoDialog.type = "add";
    infoDialog.title = "新增供应商信息";
  }
}

const adCpQueryParams = reactive<any>({
  pageNum: 1,
  pageSize: 10,
  parentCode: "",
});

//根据客户信息获取地址信息，联系人信息
function handleGetInfo() {
  suppInfoApi.getAddressPage(adCpQueryParams).then((res) => {
    addressList.value = res;
  });

  suppInfoApi.getContactPage(adCpQueryParams).then((res) => {
    contactList.value = res;
  });
}
//新增收货地址
function handleOpenAddressDialog(row?: any, type?: string) {
  if (type === "edit") {
    addressDialog.title = "修改收货地址";
    //回显数据
    Object.assign(addressParams, row);
  } else {
    if (!adCpQueryParams.parentCode) {
      ElMessage.warning("请先新增供应商");
      return;
    }
    addressDialog.title = "新增收货地址";
  }
  addressDialog.visible = true;
}

//更新默认地址
function updateAddress(type: string, row?: any) {
  let query = {
    ...row,
  };
  query[type] = 1;
  query.parentCode = adCpQueryParams.parentCode;
  suppInfoApi
    .updateAddress(query)
    .then((res) => {
      ElMessage.success("操作成功");
    })
    .finally(() => {
      suppInfoApi.getAddressPage(adCpQueryParams).then((res) => {
        addressList.value = res;
      });
    });
}

//关闭地址弹窗
function handleCloseAddressDialog() {
  addressDialog.visible = false;
  addressRef.value.resetFields();
  clearAddressFormData();
}

//保存地址信息
function handleSaveAddress() {
  addressRef.value.validate((valid: any) => {
    if (!valid) return;
    addressParams.parentCode = adCpQueryParams.parentCode;
    if (addressParams.id) {
      suppInfoApi
        .updateAddress(addressParams)
        .then((res) => {
          ElMessage.success("操作成功");
        })
        .finally(() => {
          addressDialog.visible = false;
          suppInfoApi.getAddressPage(adCpQueryParams).then((res) => {
            addressList.value = res;
          });
        });
    } else {
      suppInfoApi
        .addAddress(addressParams)
        .then((res) => {
          ElMessage.success("操作成功");
        })
        .finally(() => {
          addressDialog.visible = false;
          suppInfoApi.getAddressPage(adCpQueryParams).then((res) => {
            addressList.value = res;
          });
        });
    }
  });
}
//删除地址信息
function deleteAddress(id: number) {
  ElMessageBox.confirm("是否确认删除该地址信息？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      suppInfoApi.deleteAddressById(id).then((res) => {
        ElMessage.success("操作成功");
      });
    })
    .catch((err) => {
      ElMessage.info("已取消删除");
    })
    .finally(() => {
      suppInfoApi.getAddressPage(adCpQueryParams).then((res) => {
        addressList.value = res;
      });
    });
}

//打开联系人弹窗
function handleOpenContactDialog(contact?: any) {
  if (contact.id) {
    contactDialog.title = "修改联系人";
    Object.assign(contactPersonParams, contact);
  } else {
    if (!adCpQueryParams.parentCode) {
      ElMessage.warning("请先新增供应商");
      return;
    }
    contactDialog.title = "新增联系人";
  }
  contactDialog.visible = true;
}

//保存联系人
function handleSaveContact() {
  contactRef.value.validate((valid: any) => {
    if (!valid) return false;
    contactPersonParams.parentCode = adCpQueryParams.parentCode;
    if (contactPersonParams.id) {
      suppInfoApi
        .updateContact(contactPersonParams)
        .then((res) => {
          ElMessage.success("操作成功");
        })
        .finally(() => {
          contactDialog.visible = false;
          suppInfoApi.getContactPage(adCpQueryParams).then((res) => {
            contactList.value = res;
          });
        });
    } else {
      suppInfoApi
        .addContact(contactPersonParams)
        .then((res) => {
          ElMessage.success("操作成功");
        })
        .finally(() => {
          contactDialog.visible = false;
          suppInfoApi.getContactPage(adCpQueryParams).then((res) => {
            contactList.value = res;
          });
        });
    }
  });
}

//关闭联系人弹窗
function handleCloseContactDialog() {
  contactDialog.visible = false;
  contactRef.value.resetFields();
  //清空所有数据
  contactPersonParams.id = NaN;
  contactPersonParams.contactPerson = undefined;
  contactPersonParams.department = undefined;
  contactPersonParams.position = undefined;
  contactPersonParams.tel = undefined;
  contactPersonParams.email = undefined;
  contactPersonParams.remark = undefined;
}

//删除联系人
function deleteContact(id: number) {
  ElMessageBox.confirm("是否确认删除该联系人？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      suppInfoApi.deleteContactById(id).then((res) => {
        ElMessage.success("操作成功");
      });
    })
    .catch((err) => {
      ElMessage.warning(err.message || "已取消删除");
    })
    .finally(() => {
      suppInfoApi.getContactPage(adCpQueryParams).then((res) => {
        contactList.value = res;
      });
    });
}

// 清空供应商表单数据
function clearFormData() {
  let data = {
    id: undefined,
    code: "", // 供应商编号
    salesMan: "", // 跟进业务员
    companyName: "", // 中文名称
    otherName: "", // 英文名称
    nickName: "", // 简称
    contactPerson: "", // 主要联系人
    status: undefined, // 状态
    creditDeadline: "", // 授信截止时间
    website: "", // 公司网站
    accCode: "", // 对应财务系统编号
    accName: "", // 对应财务系统名称
    bankInfo: "", // 银行信息
    bankName: "", // 银行名称
    remark: "", // 备注
    fileInfoJson: "", // 附件信息，初始化为空数组
    suppType: 0,
  };
  Object.assign(infoFormData, data);
  checkAll.value = false;
  isIndeterminate.value = false;
  checkedSuppTypes.value = [];
}

function clearAddressFormData() {
  let data = {
    id: undefined,
    addressName: "",
    address: "", // 收货地址
    contactPerson: "", // 联系人
    tel: "", // 联系电话
    email: "", // 邮箱
    isDefault: 0, // 是否默认地址
    isBilling: 0, // 是否账单地址
    isShipping: 0, // 是否发货地址
    remark: "", // 备注
  };
  Object.assign(addressParams, data);
}

// 关闭弹窗
function handleCloseDialog() {
  infoDialog.visible = false;

  checkedSuppTypes.value = [];
  infoFormRef.value?.clearValidate();
  infoFormRef.value?.resetFields();
  adCpQueryParams.parentCode = undefined;
  //清空地址和联系人数据
  addressList.value = [];
  contactList.value = [];
  submitButtonDisabled.value = false;
  clearFormData();
}

function handleUpdateFileInfoJson(file: any) {
  let submitFileInfo = JSON.parse(infoFormData.fileInfoJson || "[]");
  submitFileInfo = [file[file.length - 1], ...submitFileInfo];
  infoFormData.fileInfoJson = JSON.stringify(submitFileInfo);
}
//基础信息提交
function handleSubmitBase() {
  infoFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return;
    }
    //累加所有value
    if (JSON.parse(infoFormData.fileInfoJson || "[]").length === 0) {
      ElMessage.error("请上传附件");
      return;
    }
    infoFormData.suppType = checkedSuppTypes.value?.join(",");

    if (infoDialog.type == "update") {
      suppInfoApi
        .update({ ...infoFormData })
        .then((data: any) => {
          ElMessage.success("提交成功");
          handleCloseDialog();
        })
        .catch((err) => {
          // ElMessage.error(`${err}`);
          // handleCloseDialog();
          handleResetQuery();
        })
        .finally(() => {
          handleQuery();
        });
    } else {
      suppInfoApi
        .add({ ...infoFormData })
        .then((data: any) => {
          ElMessage.success("提交成功");
          adCpQueryParams.parentCode = data;
          submitButtonDisabled.value = true;
          //跳转到新增地址和联系人
          activeTabsName.value = "联系人信息";
        })
        .catch((err) => {
          // ElMessage.error(`${err}`);
          // handleCloseDialog();
          handleResetQuery();
        })
        .finally(() => {
          handleQuery();
        });
    }
    fileInfoJson.value = [];
  });
}

/**
 * 删除供应商信息
 * @param  id? number 供应商信息id
 * @returns
 */

function handleDelete(id: number) {
  ElMessageBox.confirm("确认删除供应商信息?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      suppInfoApi
        .deleteById(id)
        .then((data) => {
          ElMessage.success("删除成功");

          handleQuery();
        })
        .catch((err) => {
          // ElMessage.error(`${err}`);
          handleQuery();
        })
        .finally(() => {
          handleQuery();
          loading.value = false;
        });
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}

//下载附件
function downloadFile(name: string, filePath: string) {
  if (filePath) {
    FileAPI.downloadFile(filePath, name)
      .then(() => {
        ElMessage.success("下载成功");
      })
      .catch(() => {
        // ElMessage.error(`${err}`);
      });
  }
}

//删除附件
function deleteFile(index: number) {
  let submitFileInfo = JSON.parse(infoFormData.fileInfoJson || "[]");
  submitFileInfo.splice(index, 1);
  fileInfoJson.value.splice(index, 1);
  infoFormData.fileInfoJson = JSON.stringify(submitFileInfo);
}
const disabledDate = (time: Date) => {
  const startDate = new Date();
  startDate.setHours(0, 0, 0, 0); // 设置开始日期为当天的开始时间
  return time.getTime() < startDate.getTime();
};

//打开跟进弹窗
function handleOpenFollowDialog(row: any) {
  followDialog.visible = true;
  followDialog.title = "跟进记录";
  followParams.companyCode = row.code;
  followParams.salesMan = row.salesMan;
  followParams.followContactPerson = JSON.parse(sessionStorage.getItem("USER_INFO")!).account;
  followParams.contactType = JSON.parse(sessionStorage.getItem("USER_INFO")!).phone;
  const now = new Date();
  followParams.followDate = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")} ${String(now.getHours()).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}:${String(now.getSeconds()).padStart(2, "0")}`;
}

//保存跟进记录
function handleSaveFollow() {
  followRef.value?.validate((valid: boolean) => {
    if (!valid) {
      return;
    }
    salesApi
      .add({ ...followParams })
      .then((data) => {
        ElMessage.success("保存成功");
      })
      .catch((err) => {
        // ElMessage.error(`${err}`);
      })
      .finally(() => {
        handleQuery();
        followDialog.visible = false;
      });
  });
}
//关闭跟进弹窗
function handleCloseFollowDialog() {
  followDialog.visible = false;
  followRef.value?.clearValidate();
  followParams.followContactPerson = "";
  followParams.followDate = "";
  followParams.remark = "";
  followParams.contactType = "";
}

//打开跟进查看弹窗
function handleOpenFollowViewDialog(row: any) {
  followList.value = [];
  let queryParams = {
    id: row.id,
    pageSize: 10,
    pageNum: 1,
    companyCode: row.code,
  };

  followViewDialog.visible = true;
  followViewDialog.title = "跟进记录";
  salesApi
    .getList(queryParams)
    .then((data) => {
      followList.value = data.list;
    })
    .catch((err) => {
      // ElMessage.error(`${err}`);
    });
}

//删除跟进记录
function deleteRecord(row: any) {
  ElMessageBox.confirm("确认删除跟进记录?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      salesApi
        .delete(row.id)
        .then((data) => {
          ElMessage.success("删除成功");
        })
        .catch((err) => {
          // ElMessage.error(`${err}`);
        })
        .finally(() => {
          salesApi
            .getList({ companyCode: row.companyCode })
            .then((data) => {
              followList.value = data.list;
            })
            .catch((err) => {
              // ElMessage.error(`${err}`);
            });
          loading.value = false;
        });
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}

//关闭跟进查看弹窗
function handleCloseFollowViewDialog() {
  followViewDialog.visible = false;
  followList.value = [];
}

//查询所有供应商和业务员信息
function handleAllCompanyQuery() {
  suppInfoApi.getPage({ pageNum: 1, pageSize: 999 }).then((data: any) => {
    allCompanyCode.value = data.records.map((item: any, idx: number) => ({
      value: item.code,
      label: `${item.code} - ${item.companyName}`,
    }));
  });
  UserAPI.getPage({ pageNum: 1, pageSize: 999, roleName: "salesMan" }).then((data) => {
    salesPersonList.value = data.list.map((item: any) => ({
      value: item.id,
      label: item.name,
    }));
  });
}

onMounted(() => {
  handleQuery();
  handleAllCompanyQuery();
  getSuppTypeList();
});
</script>
